from backend.services.product_service import ProductService
from backend.services.order_service import OrderService
from backend.services.address_service import AddressService
from backend.services.after_sales_service import AfterSalesService
from backend.services.chat_service import ChatService
from backend.nlp.xunfei_api import XunfeiLLM


def handle_intent(intent_type, entities, text, user_id):
    """根据意图类型调用相应服务"""
    try:
        if intent_type == 'product_query':
            return handle_product_query(entities)
        elif intent_type == 'order_query':
            return handle_order_query(entities, user_id)  # 参数顺序正确
        elif intent_type == 'address_query':
            return handle_address_query(entities, text, user_id)
        elif intent_type == 'after_sales_query':
            return handle_after_sales_query(entities, text, user_id)
        else:
            return handle_general_query(text, user_id)
    except Exception as e:
        return f"处理请求时出错：{str(e)}"


def handle_product_query(entities):
    """处理产品查询意图"""
    try:
        product_service = ProductService()

        # 1. 如果有特定产品ID
        if 'product_id' in entities:
            product = product_service.get_product_by_id(entities['product_id'])
            if product:
                return (f"产品信息：\n名称: {product['name']}\n"
                        f"价格: {product['price']}元\n"
                        f"库存: {product['stock']}件\n"
                        f"功效: {product['effect']}\n"
                        f"适用肤质: {product['skin_type']}")
            else:
                return f"未找到产品ID为{entities['product_id']}的产品"

        # 2. 如果有推荐类型（如洁面产品）
        elif 'product_type' in entities:
            # 根据产品类型搜索
            products = product_service.search_products(entities['product_type'])

            if products:
                response = f"为您推荐以下{entities['product_type']}产品：\n"
                for i, p in enumerate(products[:3], 1):  # 最多推荐3个
                    response += (f"{i}. {p['name']} (ID: {p['product_id']})\n"
                                 f"  价格: {p['price']}元\n"
                                 f"  功效: {p['effect']}\n\n")
                return response
            else:
                return f"抱歉，没有找到{entities['product_type']}产品"

        # 3. 如果有产品名称
        elif 'product_name' in entities:
            products = product_service.search_products(entities['product_name'])
            if products:
                response = f"找到以下{len(products)}个相关产品：\n"
                for i, p in enumerate(products[:5], 1):
                    response += f"{i}. {p['name']} (ID: {p['product_id']}, 价格: {p['price']}元)\n"
                return response
            else:
                return f"未找到名称包含{entities['product_name']}的产品"

        # 4. 没有提供足够信息
        else:
            return "请提供具体的产品ID或名称，以便我为您查询信息"
    except Exception as e:
        return f"查询产品信息时出错：{str(e)}"


def handle_order_query(entities, user_id):
    """处理订单查询意图"""
    try:
        order_service = OrderService()

        # 1. 如果有订单ID
        if 'order_id' in entities:
            order = order_service.get_order_by_id(user_id, entities['order_id'])
            if order:
                # 添加产品信息
                product_service = ProductService()
                product = product_service.get_product_by_id(order['product_id'])

                return (f"订单信息：\n订单号: {order['order_id']}\n"
                        f"产品: {product['name'] if product else '未知产品'}\n"
                        f"金额: {order['total_price']}元\n"
                        f"状态: {order['status']}\n"
                        f"下单时间: {order['order_time'].strftime('%Y-%m-%d %H:%M')}")
            else:
                # 检查订单是否存在
                if order_service.order_exists(entities['order_id']):
                    return f"订单{entities['order_id']}存在，但不属于您的账户"
                else:
                    return f"未找到订单号为{entities['order_id']}的订单"

        # 2. 没有订单ID，查询用户所有订单
        else:
            orders = order_service.get_user_orders(user_id)
            if orders:
                response = f"您有{len(orders)}个订单：\n"
                for o in orders:
                    # 简化日期格式
                    order_date = o['order_time'].strftime('%m-%d') if o['order_time'] else '未知日期'
                    response += f"- 订单号: {o['order_id']}, 产品: {o['product_name']}, 状态: {o['status']}, 下单时间: {order_date}\n"
                response += "\n请输入订单号查看详细信息"
                return response
            else:
                return "您当前没有任何订单"
    except Exception as e:
        return f"查询订单时出错：{str(e)}"


def handle_address_query(entities, text, user_id):
    """处理地址查询意图"""
    try:
        # 检查是否提供了订单号
        order_id = entities.get('order_id')

        if not order_id:
            return "请提供您要修改地址的订单号"

        # 检查是否提供了新地址
        new_address = entities.get('new_address')

        if not new_address:
            return "请输入新的收货地址"

        # 调用地址服务
        address_service = AddressService()
        success, message = address_service.update_shipping_address(user_id, order_id, new_address)

        return message
    except Exception as e:
        return f"处理地址修改时出错: {str(e)}"


def handle_after_sales_query(entities, text, user_id):
    """处理售后服务意图"""
    try:
        # 检查是否提供了订单号
        order_id = entities.get('order_id')

        if not order_id:
            return "请提供您要申请售后的订单号"

        # 获取原因（如果有）
        reason = entities.get('reason', '用户申请')

        # 调用售后服务
        after_sales_service = AfterSalesService()
        success, message = after_sales_service.create_after_sales_request(order_id, reason)

        return message
    except Exception as e:
        return f"处理售后服务时出错: {str(e)}"

def handle_general_query(text, user_id):
    """处理通用查询意图"""
    try:
        # 获取历史对话作为上下文
        chat_service = ChatService()
        history = chat_service.get_chat_history(user_id)

        # 转换为API需要的格式
        history_messages = [
            {"role": "user" if h['sender_type'] == 'user' else "assistant",
             "content": h['message']}
            for h in history[-5:]  # 只取最近5条历史
        ]

        # 添加当前消息
        messages = history_messages + [{"role": "user", "content": text}]

        # 调用讯飞API
        llm = XunfeiLLM()
        response = llm.get_answer(messages)
        return response

    except Exception as e:
        return f"处理通用查询时出错：{str(e)}"